var warehouse= require('./warehouse_client.js')
var mongoose=require('mongoose')
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/users')
//定义模型 规定数据类型 key 与表(集合) 必须一致
var newScheam=mongoose.Schema({
	name:String,
	password:String,
	_id:String,
	HeadImg:String
})
//关联表(集合) 
var mode=mongoose.model('clients',newScheam)

class operation {
	constructor(arg) {
	    this.warehouse=warehouse
	};
	//新添用户
	append(obj){
		return new Promise((resolve,reject)=>{
			var name=obj.name||null;
			var password=obj.password||null;
			var date=new Date()
			var _id=obj._id||date.getTime()
			var HeadImg=obj.HeadImg||null
			new mode({
				name,
				password,
				HeadImg,
				_id
			}).save().then(
			 result=>{
				 warehouse.append({
					 _id
				 })
				resolve('用户添加成功')
			 },
			 err=>{
				 resolve(null)
			 }
			)
		})
	};
	//查询用户是否存在
	query(query){
		//query {name,password}
		return new Promise((resolve,reject)=>{
			mode.find({...query},(err,doc)=>{
				if(err){
					resolve(null)
					return;
				}
				if(doc[0]){
					resolve(doc[0])
				}else{
					resolve(null)
				}
			})
		})
	};
	//修改用户数据
	upDate(query,parms){
		return new Promise((resolve,reject)=>{
			if(parms._id){
				reject('不能修改_id')
			}
			mode.updateOne(query,parms,(err,doc)=>{
				if(err){
					console.log('错误')
						reject(err)
						return;
					}
					resolve(doc)
			})
		})
	}
}
module.exports=new operation()
